/**
 * 
 */
package jnzb.control.util;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import jnzb.control.Configuration;
import jnzb.model.nzb.NZB;

/**
 * @author AA1
 * 
 */
public class FileUtils {

	public static void createWorkFolderStructure(NZB nzb) throws IOException {
		Configuration config = Configuration.getInstance();

		// Create the NZB root folder
		// Remove the .nzb if thats what it ends with
		String filename = config.getNZBWorkFoldername(nzb.getFilename());

		String nzbFolderPath = config.getRoot() + filename;
		java.io.File folder = new java.io.File(nzbFolderPath);
		if (!(folder.exists() && folder.isDirectory())) {
			folder.mkdirs();
		} else {
			// Folder is already there, should be able to continue
		}

		// Create sub folders for working in
		folder = new java.io.File(nzbFolderPath + "/"
				+ Configuration.NZB_FOLDER);
		folder.mkdir();

		// Copy original file over to here
		String dest = nzbFolderPath + "/" + Configuration.NZB_FOLDER + "/"
				+ nzb.getFilename();
		copyFile(nzb.getPath(), dest);

		/*
		 * No longer have parts folder, store in root folder = new
		 * java.io.File(nzbFolderPath + "/" + Configuration.PARTS_FOLDER);
		 */
		folder.mkdir();
		folder = new java.io.File(nzbFolderPath + "/"
				+ Configuration.SEGMENT_FOLDER);
		folder.mkdir();
	}

	public static void copyFile(String src, String dst) throws IOException {
		InputStream in = new FileInputStream(src);
		OutputStream out = new FileOutputStream(dst);

		// Transfer bytes from in to out
		byte[] buf = new byte[1024];
		int len;
		while ((len = in.read(buf)) > 0) {
			out.write(buf, 0, len);
		}
		in.close();
		out.close();
	}

	/**
	 * Remove the segments folder and all files in it
	 */
	public static void deleteDirectory(String dir) {

	}

	/**
	 * Finally close a stream - discard exception
	 * @param fos
	 */
	public static void close(OutputStream os) {
		if (os!=null){
			try {
				os.close();
			} catch (IOException e) {
				// discard
			}
		}
	}

	/**
	 * Finally close a stream - discard exception
	 * @param fis
	 */
	public static void close(InputStream is) {
		if (is!=null){
			try {
				is.close();
			} catch (IOException e) {
				// discard
			}
		}
		
	}

}
